import { createRouter, createWebHistory } from 'vue-router'

import importItemview from '../views/importItem.vue'
import QuestionView from '../views/Question.vue'
import qHomeView from '../views/qHome.vue'
import Login from '../views/Login.vue'
import Logout from '../views/Logout.vue'
import UserManagement from '../views/UserManagement.vue'
import homeview from '../views/HomeView.vue'


const  routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { layout: 'empty' }
  },
  {
    path: '/logout',
    name: 'Logout',
    component: Logout,
    meta: { layout: 'empty' }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: { requiresAuth: true,layout: 'main' }
  },
  {
    path: '/', 
    redirect: '/homeview'  // 默认路由重定向到登录页
  },    
  {
    path: '/homeview',
    name: 'homeview',
    component: homeview,
    meta: { requiresAuth: true,layout: 'main' },
    children: [
      {
        path: '/importItem',
        name: 'importItem',
        component: importItemview,
        meta: { requiresAuth: true }
      },
      {
        path: '/queryItem',
        name: 'queryItem',
    // route level code-splitting
    // this generates a separate chunk (About.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
        component: () => import('../views/queryItem.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/Question',
        name: 'Question',
        component:  QuestionView,
        meta: { requiresAuth: true }
    
      },
      {
        path: '/qHome',
        name: 'qHome',
        component:  qHomeView,
        meta: { requiresAuth: true }
    
      }
    ]
  }
];


const router = createRouter({

  history: createWebHistory(import.meta.env.BASE_URL),
  routes

})
// 导航守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = checkAuth() // 检查是否登录

  // 已登录时禁止访问登录页
  if (to.path === '/login' && isAuthenticated) {
    next('/') // 重定向到首页
    return
  }

  // 检查目标路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 携带原路径
      })
    } else {
      next()
    }
  } else {
    next() // 不需要认证的路由直接放行
  }
})

// 简单检查本地是否有token
function checkAuth() {
  return localStorage.getItem('token') !== null
}

export default router;

